<template>
  <!-- 教师页面 -->
  <el-container class="h-full">
    <el-header class="border-b border-gray-200">
      <div class="w-full h-full flex justify-between items-center">
        <div class="text-xl font-bold">教师教辅平台</div>
        <div class="flex items-center gap-4">
          <div class="text-base font-bold">{{ userInfo.name }}</div>
          <el-button type="primary" size="small" @click="logout"
            >退出登录</el-button
          >
        </div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="200px" class="border-r border-gray-200">
        <el-menu
          :default-active="activeMenu"
          class="h-full"
          @select="handleMenuSelect"
        >
          <el-menu-item index="courses">
            <el-icon><VideoPlay /></el-icon>
            <span>课程管理</span>
          </el-menu-item>
          <el-menu-item index="assignments">
            <el-icon><Document /></el-icon>
            <span>作业管理</span>
          </el-menu-item>
          <el-menu-item index="sign">
            <el-icon><Document /></el-icon>
            <span>签到管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <component
          v-if="currentComponent"
          :is="currentComponent"
          ref="homeworkRef"
          @publish="assignmentDialogVisible = true"
        />
      </el-main>
    </el-container>
  </el-container>

  <!-- 课件管理对话框 -->
  <el-dialog v-model="materialsDialogVisible" title="课件管理" width="600px">
    <div v-if="currentCourse">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-bold">{{ currentCourse.title }}</h3>
        <div v-if="courseForm.file">
          <span>{{ courseForm.file.name }}</span>
          <el-button type="danger" link @click="deleteMaterial">
            删除
          </el-button>
        </div>

        <el-button type="primary" @click="handleMaterialUpload">
          上传课件
        </el-button>
      </div>
      <div class="video-section mb-4">
        <h4 class="font-bold mb-2">课程视频</h4>
        <div
          class="video-player bg-black h-[200px] mb-2 flex justify-center items-center"
        >
          <el-icon v-if="!currentCourse.videoUrl" :size="40" class="text-white"
            ><VideoPlay
          /></el-icon>
          <video v-else controls class="w-full h-full">
            <source :src="currentCourse.videoUrl" type="video/mp4" />
          </video>
        </div>
      </div>
      <div class="materials-section">
        <h4 class="font-bold mb-2">课件列表</h4>
        <div v-if="currentCourse.materials?.length">
          <div
            v-for="(material, index) in currentCourse.materials"
            :key="index"
            class="p-2 border-b border-gray-200 flex justify-between items-center"
          >
            <div class="flex items-center">
              <el-icon class="mr-2"><Document /></el-icon>
              <span>{{ material.name }}</span>
            </div>
            <el-button type="danger" link @click="deleteMaterial(index)"
              >删除</el-button
            >
          </div>
        </div>
        <el-empty v-else description="暂无课件资料"></el-empty>
      </div>
    </div>
  </el-dialog>

  <!-- 发布作业对话框 -->
  <TaskDialog
    v-model="assignmentDialogVisible"
    v-model:data="assignmentForm"
    :courseList="courseList"
    @cancel="assignmentDialogVisible = false"
    @save="saveAssignment"
    @upload="uploadTaskFile"
  />

  <!-- 编辑成绩对话框 -->
  <el-dialog v-model="gradeDialogVisible" title="编辑成绩" width="500px">
    <el-form :model="gradeForm" label-width="80px">
      <el-form-item label="课程">
        <div>{{ currentGrade?.course }}</div>
      </el-form-item>
      <el-form-item label="作业">
        <div>{{ currentGrade?.assignment }}</div>
      </el-form-item>
      <el-form-item label="学生">
        <div>{{ currentGrade?.student }}</div>
      </el-form-item>
      <el-form-item label="分数">
        <el-input-number
          v-model="gradeForm.score"
          :min="0"
          :max="100"
          :step="1"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="评语">
        <el-input
          v-model="gradeForm.feedback"
          type="textarea"
          rows="4"
          placeholder="请输入评语"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="gradeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGrade">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  ElMessage,
  type FormInstance,
  type UploadUserFile,
} from "element-plus";
import {
  VideoPlay,
  Document,
  Calendar,
  DataAnalysis,
  Plus,
} from "@element-plus/icons-vue";
import ProjectDialog from "./components/ProjectDialog.vue";
import { useProject } from "./composables/useProject";
import { useCourse } from "./composables/useCourse";
import { useUserStore } from "../../store/user";
import ProjectTable from "./components/ProjectTable.vue";
import { useTask } from "./composables/useTask";
import TaskDialog from "./components/TaskDialog.vue";
import Score from "./components/Score.vue";
import Project from "./components/Project.vue";
import Homework from "./components/Homework.vue";
import Sign from "./components/Sign.vue";
const { userInfo } = useUserStore();
const { courseList, getCourseList } = useProject();
getCourseList(userInfo.value.id);
const { currentCourse, courseForm, handleMaterialUpload, deleteMaterial } =
  useCourse();

const router = useRouter();
const activeMenu = ref("courses");

const currentComponent = computed(() => {
  if (activeMenu.value === "courses") {
    return Project;
  } else if (activeMenu.value === "assignments") {
    return Homework;
  } else if (activeMenu.value === "attendance") {
    return Sign;
  } else if (activeMenu.value === "grades") {
    return Score;
  } else if (activeMenu.value === "sign") {
    return Sign;
  }
});

// 签到列表
const attendanceList = ref([
  {
    id: 1,
    course: "高等数学",
    startTime: "2023-10-10 09:00",
    endTime: "2023-10-10 09:30",
    signedCount: 35,
    status: "已结束",
  },
  {
    id: 2,
    course: "大学物理",
    startTime: "2023-10-10 10:00",
    endTime: "2023-10-10 10:30",
    signedCount: 28,
    status: "进行中",
  },
]);

// 成绩列表
const grades = ref([
  {
    id: 1,
    course: "高等数学",
    assignment: "高数作业一",
    student: "张三",
    score: 90,
    feedback: "做得不错，继续努力！",
  },
  {
    id: 2,
    course: "大学物理",
    assignment: "物理实验报告",
    student: "李四",
    score: 85,
    feedback: "实验数据分析有待提高",
  },
  {
    id: 3,
    course: "计算机基础",
    assignment: "计算机编程作业",
    student: "王五",
    score: 95,
    feedback: "代码结构清晰，逻辑严谨",
  },
]);

// 课件管理相关
const materialsDialogVisible = ref(false);

// 作业管理相关
const {
  assignmentDialogVisible,
  assignmentForm,
  saveAssignment,
  uploadTaskFile,
  homeworkRef,
} = useTask();

// 签到管理相关
const attendanceDialogVisible = ref(false);
const attendanceForm = reactive({
  course: "",
  duration: 30,
});

// 成绩管理相关
const gradeDialogVisible = ref(false);
const currentGrade = ref(null);
const gradeForm = reactive({
  score: 0,
  feedback: "",
});

// 菜单选择
function handleMenuSelect(key) {
  activeMenu.value = key;
}

// 退出登录
function logout() {
  localStorage.removeItem("token");
  router.push("/login");
}

// 作业管理方法
function showAddAssignmentDialog() {
  assignmentDialogVisible.value = true;
}

function viewSubmissions(assignment) {
  // 查看作业提交情况
  console.log("查看作业提交:", assignment);

  // 如果是互改作业，可以查看互改情况
  if (assignment.isPeerReview) {
    ElMessage.info(
      `这是一个互改作业，互改截止日期: ${assignment.peerReviewDeadline}`
    );
    // 这里可以添加查看互改情况的逻辑
  }
}

function deleteAssignment(assignment) {
  ElMessage.success("作业删除成功");
  assignments.value = assignments.value.filter(
    (item) => item.id !== assignment.id
  );
}

function handleAssignmentFileChange(file) {
  // 处理作业附件上传
  console.log("作业附件上传:", file);
}

// 签到管理方法
function showAddAttendanceDialog() {
  attendanceForm.course = "";
  attendanceForm.duration = 30;
  attendanceDialogVisible.value = true;
}

function startAttendance() {
  if (!attendanceForm.course) {
    ElMessage.warning("请选择课程");
    return;
  }

  ElMessage.success("签到已开始");
  attendanceDialogVisible.value = false;

  const now = new Date();
  const endTime = new Date(now.getTime() + attendanceForm.duration * 60000);

  attendanceList.value.unshift({
    id: attendanceList.value.length + 1,
    course: attendanceForm.course,
    startTime: now.toLocaleString(),
    endTime: endTime.toLocaleString(),
    signedCount: 0,
    status: "进行中",
  });
}

function viewAttendanceDetails(attendance) {
  // 查看签到详情
  console.log("查看签到详情:", attendance);
}

function endAttendance(attendance) {
  attendance.status = "已结束";
  ElMessage.success("签到已结束");
}

// 成绩管理方法
function editGrade(grade) {
  currentGrade.value = grade;
  gradeForm.score = grade.score;
  gradeForm.feedback = grade.feedback;
  gradeDialogVisible.value = true;
}

function saveGrade() {
  if (gradeForm.score === 0) {
    ElMessage.warning("请输入分数");
    return;
  }

  if (!gradeForm.feedback.trim()) {
    ElMessage.warning("请输入评语");
    return;
  }

  const index = grades.value.findIndex(
    (item) => item.id === currentGrade.value.id
  );
  if (index !== -1) {
    grades.value[index].score = gradeForm.score;
    grades.value[index].feedback = gradeForm.feedback;
  }

  ElMessage.success("成绩更新成功");
  gradeDialogVisible.value = false;
}

// 初始化数据
onMounted(() => {
  // 这里可以调用API获取数据
});
</script>

<style scoped>
.el-header {
  height: 60px;
  line-height: 60px;
}

.el-aside {
  background-color: #fff;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>
